package com.autorun.server.controller;

import com.autorun.server.dto.ApiResponse;
import com.autorun.server.dto.CreateUserRequest;
import com.autorun.server.dto.UpdateUserRequest;
import com.autorun.server.entity.User;
import com.autorun.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器（管理员专用）
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * 
     * @return 用户列表
     */
    @GetMapping
    public ApiResponse<List<User>> getUserList() {
        try {
            List<User> users = userService.getUserList();
            return ApiResponse.success(users);
        } catch (Exception e) {
            log.error("获取用户列表失败: {}", e.getMessage(), e);
            return ApiResponse.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 创建用户
     * 
     * @param request 创建用户请求
     * @return 用户信息
     */
    @PostMapping
    public ApiResponse<User> createUser(@Valid @RequestBody CreateUserRequest request) {
        try {
            User user = userService.createUser(request);
            log.info("创建用户成功 - ID: {}, 用户名: {}", user.getId(), user.getUsername());
            return ApiResponse.success("创建用户成功", user);
        } catch (Exception e) {
            log.error("创建用户失败: {}", e.getMessage(), e);
            return ApiResponse.error("创建用户失败: " + e.getMessage());
        }
    }

    /**
     * 获取单个用户信息
     * 
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public ApiResponse<User> getUser(@PathVariable Integer id) {
        try {
            User user = userService.getUserById(id);
            return ApiResponse.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return ApiResponse.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param request 更新请求
     * @return 用户信息
     */
    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(@PathVariable Integer id, @Valid @RequestBody UpdateUserRequest request) {
        try {
            User user = userService.updateUser(id, request);
            log.info("更新用户成功 - ID: {}, 用户名: {}", user.getId(), user.getUsername());
            return ApiResponse.success("更新用户成功", user);
        } catch (Exception e) {
            log.error("更新用户失败: {}", e.getMessage(), e);
            return ApiResponse.error("更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 成功消息
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteUser(@PathVariable Integer id) {
        try {
            userService.deleteUser(id);
            log.info("删除用户成功 - ID: {}", id);
            return ApiResponse.success("删除用户成功");
        } catch (Exception e) {
            log.error("删除用户失败: {}", e.getMessage(), e);
            return ApiResponse.error("删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     * 
     * @param id 用户ID
     * @param request 包含新密码的请求体
     * @return 成功消息
     */
    @PostMapping("/{id}/reset-password")
    public ApiResponse<Void> resetUserPassword(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        try {
            String newPassword = request.get("new_password");
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return ApiResponse.error("新密码不能为空");
            }
            if (newPassword.length() < 6) {
                return ApiResponse.error("密码长度不能少于6位");
            }
            
            userService.resetUserPassword(id, newPassword);
            log.info("重置密码成功 - 用户ID: {}", id);
            return ApiResponse.success("重置密码成功");
        } catch (Exception e) {
            log.error("重置密码失败: {}", e.getMessage(), e);
            return ApiResponse.error("重置密码失败: " + e.getMessage());
        }
    }
}